package handler

import (
	"context"
	"fmt"
	"zg5/videos/common/global"
	"zg5/videos/common/models"
	"zg5/videos/common/proto/videos"
)

type Server struct {
	videos.UnimplementedVideoSrvServer
}

func (s *Server) AddVideo(_ context.Context, req *videos.AddVideoRequest) (*videos.AddVideoResponse, error) {

	video := models.Videos{
		UserId:       req.UserId,
		Name:         req.Name,
		Format:       req.Format,
		Size:         req.Size,
		TypesId:      req.TypesId,
		UploadMethod: uint8(req.UploadMethod),
		Addr:         uint8(req.Addr),
		Recommend:    uint8(req.Recommend),
	}

	if err := global.DB.Debug().Create(&video).Error; err != nil {
		return nil, fmt.Errorf("视频发布失败")
	}

	return &videos.AddVideoResponse{}, nil
}
func (s *Server) VideoList(_ context.Context, req *videos.VideoListRequest) (*videos.VideoListResponse, error) {
	page := req.Page
	if page <= 0 {
		page = 1
	}
	pageSize := req.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	query := global.DB.Model(&models.Videos{})
	if req.Status != 0 {
		query.Where("status = ?", req.Status)
	}
	if req.UserId != 0 {
		query.Where("user_id = ?", req.UserId)
	}
	
	offset := (page - 1) * pageSize
	var videoList []models.Videos
	query.Offset(int(offset)).Limit(int(pageSize)).Find(&videoList)

	var lists []*videos.VideoList

	for _, v := range videoList {
		lists = append(lists, &videos.VideoList{
			UserId:       v.UserId,
			Name:         v.Name,
			Format:       v.Format,
			Size:         v.Size,
			TypesId:      v.TypesId,
			UploadMethod: uint64(v.UploadMethod),
			Addr:         uint64(v.Addr),
		})
	}
	return &videos.VideoListResponse{
		List: lists,
	}, nil
}
